//
//  VideoGamesVC.swift
//  d11
//
//  Created by peale on 2018/10/4.
//  Copyright © 2018年 Tech_001. All rights reserved.
//

import UIKit

class VideoGamesVC: BXBaseVC,UICollectionViewDelegate,UICollectionViewDataSource {
    let  reuseIdentifierID = "VideoGamesCell" //70x70
    //let cellHeadReuseIdentifierID = @"ExploreHeadView";
    var platform: [String:Any]?
    var subGameList: [[String:Any]]?
    var isRotate: Bool = false
    var isBack : Bool = false
    var balanceButton: UIButton?
 lazy var collectionView:UICollectionView = {
    let layout = UICollectionViewFlowLayout.init()
    if kIsIpad == true {
        layout.itemSize = CGSize(width: kScreenWidth/6, height: 100)
    }else{
         layout.itemSize = CGSize(width: kScreenWidth/3, height: 100)
    }
    
    layout.minimumLineSpacing = 0
    layout.minimumInteritemSpacing = 0
        layout.scrollDirection = .vertical
    //   layout.sectionInset = UIEdgeInsets.init(top: 5, left: 5, bottom: 5, right: 5)
    // 设置分区头视图和尾视图宽高
    //    layout.headerReferenceSize = CGSize.init(width: kScreenWidth, height: 80)
    //    layout.footerReferenceSize = CGSize.init(width: kScreenWidth, height: 80)
    
    let collView = UICollectionView.init(frame: CGRect(x:0, y:20, width:kScreenWidth, height:kScreenHeight-20), collectionViewLayout: layout)
 
    if collView.responds(to:#selector(setter: UIView.layoutMargins)) {
        collView.layoutMargins = .zero;
    }
    collView.autoresizingMask = UIView.AutoresizingMask.flexibleWidth.union(UIView.AutoresizingMask.flexibleHeight)
    collView.register(VideoGamesCell.self, forCellWithReuseIdentifier: "VideoGamesCell")
  //  [_collectionView registerClass:[ExploreHeadView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:cellHeadReuseIdentifierID];
    collView.showsVerticalScrollIndicator = false
    collView.showsHorizontalScrollIndicator = false
    collView.backgroundColor = UIColor.white
    collView.delegate = self
    collView.dataSource = self
   return collView
 }()
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
        if self.isRotate{
            UIInterfaceOrientationMask.allButUpsideDown
        }
        return UIInterfaceOrientationMask.portrait
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.navigationItem.titleView = UIImageView.init(image: UIImage.init(named: "navi_icon_titleLogo"))
        self.navigationController?.navigationBar.shadowImage = UIImage()
        
        let item = UIBarButtonItem(title: "", style: .plain, target: self, action: nil)
        self.navigationItem.backBarButtonItem = item
        
        // 设置导航栏默认返回按钮
        self.leftButtonActionWithImg("icon_default_back")
        
        self.balanceButton = self.initRightBarBtn()
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: balanceButton!)
        self.view.backgroundColor = UIColor.white
        self.view.addSubview(self.collectionView)
         self.refreshBalance()
        
    }
    
    @objc func loginRegisterButtonClick(){
        setRootLoginVC()
    }
    
    func refreshBalance(){
        if UserHelper.getLoginStatus() {
            print("\(String(describing: GlobalInfo.memberInfoData))")
            if let withBalance = GlobalInfo.memberInfoData!["balance"] as? String {
                if withBalance != ""{
                    let balance: Double = Double(withBalance)!
                    self.balanceButton?.setTitle(String(format: "%.2f", balance), for: .normal)
                    let size = self.balanceButton!.intrinsicContentSize
                    balanceButton!.frame.size = CGSize(width: size.width, height: 33)
                }else{
                    self.balanceButton?.setTitle(String(format: "0.00"), for: .normal)
                }
            }
        }else{
            let button1 = UIBarButtonItem(title: "注册/登录", style: .plain, target: self, action: #selector(self.loginRegisterButtonClick))
            button1.tintColor = HexRGBAlpha(0xFBBC64,1)
            self.navigationItem.setRightBarButtonItems([button1], animated: false)
        }
    }
    
    //获取会员信息
    func getUserInfo() -> Void {
        if UserHelper.getLoginStatus() {
            //api2.0接口开始
            NetWorkRequest(API.memberInfoUL(url: "face82b", ccToken: API.getCcToken(), vcToken: API.getVcToken()), completion:  { (responseData,statusCode,strData) -> (Void) in
                if(statusCode == 200){
                    //取出data的数据并转化为字典数据
                    let dataDict = responseData["data"].dictionaryObject
                    //获取到状态值
                    let statusStringJson = responseData["status"]
                    //把状态值的字符串转为int值
                    let statusString = Int("\(statusStringJson)")
                    //获取到传递过来的msg
                    let msgStringJson = responseData["msg"]
                    //把msgStringJson转为字符串
                    let msgString = "\(msgStringJson)"
                    //判断是否相等的
                    if(statusString == 0){
                        let memberInfoArray = dataDict?["response"] as? [String:Any] ?? [:]
                        GlobalInfo.memberInfoData = memberInfoArray
                        print("用户信息: \(memberInfoArray),\(String(describing: GlobalInfo.memberInfoData))")
                        DispatchQueue.main.async {
                            self.refreshBalance()
                        }
                    }else{
                        DispatchQueue.main.async {
                            //弹出报错后的问题
                            UIHelper.alertSimpleMessage(about: msgString, withDescription: "", in: self)
                        }
                    }
                    
                }else{
                    DispatchQueue.main.async {
                        //弹出报错后的问题
                        UIHelper.alertSimpleMessage(about: "获取用户信息失败!", withDescription: "", in: self)
                    }
                }
            },failed: {(faildInfo,reCode,msg) -> (Void) in
                DispatchQueue.main.async {
                    if reCode == "21002"{
             //           UIHelper.displayLoginExpireTip(self)
                    }else{
                        UIHelper.alertSimpleMessage(about: "\(faildInfo)", withDescription: "", in: self)
                    }
                }
          
            }){() -> (Void) in
                DispatchQueue.main.async {
                    UIHelper.alertSimpleMessage(about: "网络请求异常!", withDescription: "", in: self)
                    
                }
            }
            //api2.0接口结束
            
            
            
            
            
//            RequestHelper.get(atPath: "/clientsAPIs/memberInfoUL", withCompletion: { data in
//                let memberInfoArray = try JSONSerialization.jsonObject(with: data, options: []) as! [String: Any]
//                GlobalInfo.memberInfoData = memberInfoArray
//                print("用户信息: \(memberInfoArray),\(String(describing: GlobalInfo.memberInfoData))")
//                DispatchQueue.main.async {
//                    self.refreshBalance()
//                }
//            }, withError: { error in
//                UIHelper.alertSimpleMessage(about: "服务器异常,\(getErrorString())", withDescription: "", in: self)
//            })
        }
    }
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return subGameList!.count
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize.init(width: 0, height: 0)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
        return CGSize.init(width: 0, height: 0)
    }
    
    //设定header和footer的方法，根据kind不同进行不同的判断即可
//    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
//        if kind == UICollectionElementKindSectionHeader{
//            let headerView : CollectionHeaderView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: headerIdentifier, for: indexPath) as! CollectionHeaderView
//            headerView.view.backgroundColor = UIColor.red
//            headerView.label.text = "This is HeaderView"
//            return headerView
//        }else{
//            let footView : CollectionFootView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionFooter, withReuseIdentifier: footIdentifier, for: indexPath) as! CollectionFootView
//            footView.view.backgroundColor = UIColor.purple
//            footView.label.text = "This is Foot"
//            return footView
//        }
//    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell:VideoGamesCell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifierID, for: indexPath) as! VideoGamesCell
        cell.setData(dict: subGameList![indexPath.row])
        return cell
    }
    
 
    func armColor()->UIColor{
        let red = CGFloat(arc4random()%256)/255.0
        let green = CGFloat(arc4random()%256)/255.0
        let blue = CGFloat(arc4random()%256)/255.0
        return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        //print(indexPath.row)
        
        let game = subGameList![indexPath.row]
        if game["has_sub"] != nil {
            let vc = VideoGamesVC()
            vc.platform = platform
            vc.subGameList = game["games"] as? [[String:Any]]
            self.navigationController?.pushViewController(vc, animated: true)
        }else{
         
            if  platform?["name"] as! String == "pg电游" {
                
                let goNext = GameWebViewController.instanceFromStoryboard()!
                goNext.gpid = (platform?["gpid"] as! String)
                goNext.url = (platform?["url"] as! String) + (game["title"] as! String)
                goNext.hidesBottomBarWhenPushed = true
                self.navigationController?.pushViewController(goNext, animated: true)
            }else if platform?["name"] as! String == "万博捕鱼"{
                
                let goNext = GameWebViewController.instanceFromStoryboard()!
                goNext.gpid = (platform?["gpid"] as! String)
                goNext.url = (platform?["url"] as! String) + (game["name"] as! String)
                goNext.hidesBottomBarWhenPushed = true
                self.navigationController?.pushViewController(goNext, animated: true)
            }else {
                
                let goNext = GameWKWebViewController.instanceFromStoryboard()!
                goNext.gpid = (platform?["gpid"] as! String)
                goNext.url = (platform?["url"] as! String) + (game["name"] as! String)
                goNext.hidesBottomBarWhenPushed = true
                self.navigationController?.pushViewController(goNext, animated: true)
            }
        }
    }
    
    
//    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
//        return UIEdgeInsetsMake(10, 10, 10, 10);
//    }
//     //最小 item 间距
//    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
//        return 10;
//    }
//
//    //最小行间距
//    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
//        return 10;
//    }
    
}
